package com.example.njut;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.Random;

public class LoginActivity extends AppCompatActivity {
    EditText username,pwd,inputCode,editCode,editPhone;
    Button login,exit,send;
    TextView register,us,showCode;
    String yzm;
    private CheckBox saveName;
    

    dbHelper dbHelper;
    String DB_Name="mydb";
    SQLiteDatabase db;
    Cursor cursor;

    boolean flag = false;
    String sname;
    String spwd;

    char[] checkCode ={'0','1','2','3','4','5','6','7','8','9'};
    String word = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        final SharedPreferences sp = getSharedPreferences("sname",MODE_PRIVATE);

        username = (EditText)findViewById(R.id.editUsername);
        pwd = (EditText)findViewById(R.id.editPassword);
        inputCode = (EditText)findViewById(R.id.editCode);
        login = (Button)findViewById(R.id.confirm);
        exit = (Button)findViewById(R.id.exit);
        register = (TextView)findViewById(R.id.gotoRegister);
        us = (TextView)findViewById(R.id.contactUs);
        //showCode = (TextView)findViewById(R.id.textView8);
        saveName= (CheckBox) findViewById(R.id.checkBox);
        send = (Button)findViewById(R.id.sendCode);
        editCode = (EditText)findViewById(R.id.editCode);
        editPhone = (EditText)findViewById(R.id.editPhone);
        sname = sp.getString("sname","");
        spwd = sp.getString("spwd","");

        if(sp!=null&&!sname.equals("")&&sp!=null&&!spwd.equals("")){
            username.setText(sp.getString("sname",""));
            pwd.setText(sp.getString("spwd",""));
            saveName.setChecked(true);
        }
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(editPhone.getText().toString().length()>0){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<4;i++){
                                word+=checkCode[(int)(checkCode.length*Math.random())];
                            }
                            SendCode sc = new SendCode();
                            String json = sc.bowlingJson(word,editPhone.getText().toString().trim());
                            try{
                                String response = sc.post("https://open.ucpaas.com/ol/sms/sendsms",json);
                                //word = "";
                                Looper.prepare();
                                Toast.makeText(LoginActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                                Looper.loop();

                            }catch(IOException e) {
                                Looper.prepare();
                                Toast.makeText(LoginActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else{
                    Toast.makeText(LoginActivity.this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //yzm = yzm();
       /* showCode.setText(yzm());

        showCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //yzm = yzm();
                showCode.setText(yzm());
            }
        });*/
        //创建连接，并打开数据库
        dbHelper = new dbHelper(this,DB_Name,null,1);
        db = dbHelper.getWritableDatabase();
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int x =0;
                sname = username.getText().toString();
                spwd = pwd.getText().toString();
                cursor = db.query(dbHelper.TB_Name,null,null,null,null,null,"uid ASC");
                cursor.moveToFirst();
                while(!cursor.isAfterLast()){
                    if(username.getText().toString().trim().equals(cursor.getString(1))
                            &&pwd.getText().toString().trim().equals(cursor.getString(2))){
                        flag = true;
                    }
                    cursor.moveToNext();
                }
                if(flag==true&&editCode.getText().toString().equals(word)){
                    Toast.makeText(LoginActivity.this,"欢迎回来，"+username.getText().toString().trim(),Toast.LENGTH_SHORT).show();
                    flag = false;
                    Intent intent = new Intent();
                    intent.putExtra("uname",username.getText().toString());
                    intent.setClass(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    x=1;
                }else if(flag==true&&!editCode.getText().toString().equals(word)){
                    Toast.makeText(LoginActivity.this,"验证码错误！",Toast.LENGTH_SHORT).show();
                }else if(username.getText().toString().equals("admin")&&pwd.getText().toString().equals("123")){
                    Intent intent = new Intent();
                    intent.putExtra("name",username.getText().toString());
                    intent.setClass(LoginActivity.this,ManagerActivity.class);
                    startActivity(intent);
                    x=1;
                }else if(flag==false){
                    Toast.makeText(LoginActivity.this,"用户名或密码不存在，登录失败",Toast.LENGTH_SHORT).show();
                }

                if(x == 1){
                    if(saveName.isChecked()==true){
                        //SharedPreferences sp2 = getSharedPreferences("sname",MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("sname",sname);
                        editor.putString("spwd",spwd);
                        editor.commit();
                        x=0;
                    }else{
                        SharedPreferences.Editor editor = sp.edit();
                        editor.clear();
                        editor.commit();
                    }
                }
                /*if(username.getText().toString().equals("admin")&&pwd.getText().toString().equals("123")
                        &&inputCode.getText().toString().equals(showCode.getText())){
                    Intent intent = new Intent();
                    intent.putExtra("name",username.getText().toString());
                    intent.setClass(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                }else if(!username.getText().toString().equals("admin")){
                    Toast.makeText(LoginActivity.this,"用户名不存在",Toast.LENGTH_SHORT).show();
                }else if(username.getText().toString().equals("admin")&&!pwd.getText().toString().equals("123")){
                    Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LoginActivity.this,"验证码有误，请重新输入",Toast.LENGTH_SHORT).show();
                }*/
                //Toast.makeText(LoginActivity.this,"你为什么要点我？！",Toast.LENGTH_SHORT).show();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });

        us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("tel:18851901069");
                Intent intent = new Intent(Intent.ACTION_DIAL,uri);
                startActivity(intent);
            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder ab = new AlertDialog.Builder(LoginActivity.this);
                ab.setIcon(R.mipmap.logo);
                ab.setTitle("警告！");
                ab.setMessage("是否退出！");
                ab.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //finish();
                        //System.exit(0);
                        android.os.Process.killProcess( android.os.Process.myPid());
                    }
                });
                ab.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(LoginActivity.this,"Ohhhhhhhh！",Toast.LENGTH_SHORT).show();
                    }
                });
                ab.create().show();
            }
        });
    }

    public String yzm(){
        String str ="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        String str2[] = str.split(",");
        Random rand = new Random();
        int index = 0;
        String randStr = "";
        for(int i=0;i<4;i++){
            index = rand.nextInt(str2.length-1);
            randStr += str2[index];
        }
        return randStr;
    }

    long firstTime = 0;
    public boolean onKeyDown(int keyCode, KeyEvent event){
        long sendTime = System.currentTimeMillis();
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(sendTime-firstTime<2000){
                System.exit(0);
            }else{
                Toast.makeText(LoginActivity.this,"再按一次退出",Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }
}

//备忘录
    /*修改该功能流程
    a.将清空按钮改成获取，打开程序时，不会主动读取文件中的内容，只有点击按钮才能显示文字
    b.当获取的内容为空时，提示“无内容”
    c.在程序的左上角显示打开程序的时间*/

//登录界面
    /*1.设置超级管理员用户，admin/123登录，会进入到ManagerActivity
    2.注册时，不能使用admin作为用户名
    3.在main界面添加按钮（MyInfo）,点击跳转到MyInfoActivity,该界面可以显示用户的注册信息(EditText)*/